import socket

# 创建一个socket对象
# AF_INET表示使用IPv4, SOCK_STREAM表示使用TCP
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    # 1. 建立连接 - 连接到百度服务器的80端口（HTTP默认端口）
    server_address = ('www.baidu.com', 80)
    client_socket.connect(server_address)
    print("连接建立成功！")

    # 2. 构建HTTP请求（严格按照HTTP协议格式）
    http_request = (
        "GET / HTTP/1.1\r\n"
        "Host: www.baidu.com\r\n"
        "User-Agent: simple-python-client/1.0\r\n"
        "Accept: text/html\r\n"
        "Connection: close\r\n"  # 请求完成后关闭连接
        "\r\n"  # 这个空行非常重要！标识请求头结束
    )

    # 3. 发送HTTP请求
    client_socket.send(http_request.encode('utf-8'))
    print("HTTP请求已发送")

    # 4. 接收响应数据
    response = b""
    while True:
        chunk = client_socket.recv(4096)  # 每次接收4096字节
        if not chunk:
            break  # 没有更多数据了
        response += chunk

    # 5. 解码并处理响应
    response_text = response.decode('utf-8', errors='ignore')

    # 简单的解析：分离响应头和响应体
    header_end = response_text.find('\r\n\r\n')
    headers = response_text[:header_end]
    body = response_text[header_end + 4:]  # +4 跳过 \r\n\r\n

    print("=== HTTP响应头 ===")
    print(headers)
    print("\n=== 响应体（前500字符）===")
    print(body[:500])

    # 检查状态码
    if "200 OK" in headers.split('\r\n')[0]:
        print("\n✅ 请求成功！")
    else:
        print("\n❌ 请求出现问题")

except Exception as e:
    print(f"发生错误: {e}")
finally:
    # 6. 关闭连接
    client_socket.close()
    print("连接已关闭")